package com.example.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.base.exception.CustomException;
import com.example.base.response.Result;
import com.example.entity.Params;
import com.example.entity.Type;
import com.example.service.TypeService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Api(tags = "宠物类型管理")
@CrossOrigin
@RestController
@RequestMapping("/type")
public class TypeController {
    @Autowired
    private TypeService typeService;


    @GetMapping
    public Result findAll() {
        return Result.success(typeService.findAll());
    }


    @PostMapping
    public Result save(@RequestBody Type type) {
        if (type.getTypeid() == null) {
            typeService.add(type);
        } else {
            typeService.update(type);
        }
        return Result.success();
    }

    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Type> info = typeService.findBySearch(params);
        return Result.success(info);
    }

    @DeleteMapping("/{id}")

    public Result delete(@PathVariable Integer id) {


        typeService.delete(id);
        return Result.success();
    }

    @GetMapping("/export")
    public Result export(HttpServletResponse response) throws IOException {
        List<Type> all = typeService.findAll();
        if (CollectionUtil.isEmpty(all)) {
            throw new CustomException("未找到数据");
        }
        List<Map<String, Object>> list = new ArrayList<>((all.size()));
        for (Type type : all) {
            Map<String, Object> row = new HashMap<>();
            row.put("分类名称", type.getName());
            row.put("分类描述", type.getDescription());

            list.add(row);
        }
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=type.xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
        return Result.success();
    }


}
